//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Configuration;
using System.Data;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Data;
using DotNetNuke.Services.Log.EventLog;

namespace DotNetNuke.Modules.Admin.SQL
{
	partial class SQL : DotNetNuke.Entities.Modules.PortalModuleBase
	{
		protected System.Web.UI.WebControls.Label lblRunAsScript;

		#region "Private Methods"
		private void CheckSecurity()
		{
			// Verify that the current user has access to access this page
			if (!UserInfo.IsSuperUser)
			{
				Response.Redirect(Globals.NavigateURL("Access Denied"), true);
			}
		}
		#endregion

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			cmdExecute.Click += new EventHandler(cmdExecute_Click);
			cmdUpload.Click += new EventHandler(cmdUpload_Click);

			try
			{
				CheckSecurity();
				if (!Page.IsPostBack)
				{
					ConnectionStringSettingsCollection colConnections = ConfigurationManager.ConnectionStrings;
					foreach (ConnectionStringSettings objConnection in colConnections)
					{
						if (objConnection.Name.ToLower() != "localmysqlserver" && objConnection.Name.ToLower() != "localsqlserver")
						{
							cboConnection.Items.Add(objConnection.Name);
						}
					}
					cboConnection.SelectedIndex = 0;
					cmdExecute.ToolTip = Services.Localization.Localization.GetString("cmdExecute.ToolTip", this.LocalResourceFile);
					chkRunAsScript.ToolTip = Services.Localization.Localization.GetString("chkRunAsScript.ToolTip", this.LocalResourceFile);
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdExecute_Click(object sender, System.EventArgs e)
		{
			try
			{
				CheckSecurity();
				if (!String.IsNullOrEmpty(txtQuery.Text))
				{
					string connectionstring = Config.GetConnectionString(cboConnection.SelectedValue);
					if (chkRunAsScript.Checked)
					{
						string strError = DataProvider.Instance().ExecuteScript(connectionstring, txtQuery.Text);
						if (strError == Null.NullString)
						{
							lblMessage.Text = Services.Localization.Localization.GetString("QuerySuccess", this.LocalResourceFile);
						}
						else
						{
							lblMessage.Text = strError;
						}
					}
					else
					{
						IDataReader dr = DataProvider.Instance().ExecuteSQLTemp(connectionstring, txtQuery.Text);
						if (dr != null)
						{
							gvResults.DataSource = dr;
							gvResults.DataBind();
							dr.Close();
						}
						else
						{
							lblMessage.Text = Services.Localization.Localization.GetString("QueryError", this.LocalResourceFile);
						}
					}
				}
				RecordAuditEventLog(txtQuery.Text);
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}

		private void RecordAuditEventLog(string query)
		{
			LogProperties props = new LogProperties();
			props.Add(new LogDetailInfo("User", UserInfo.Username));
			props.Add(new LogDetailInfo("SQL Query", query));

			EventLogController elc = new EventLogController();
			elc.AddLog(props, PortalSettings, UserId, EventLogController.EventLogType.HOST_SQL_EXECUTED.ToString(), true);
		}

		private void InitializeComponent()
		{
		}
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			InitializeComponent();
		}
		protected void cmdUpload_Click(object sender, System.EventArgs e)
		{
			CheckSecurity();
			if (Page.IsPostBack)
			{
				if (!String.IsNullOrEmpty(uplSqlScript.PostedFile.FileName))
				{
					System.IO.StreamReader scriptFile = new System.IO.StreamReader(uplSqlScript.PostedFile.InputStream);
					txtQuery.Text = scriptFile.ReadToEnd();
				}
			}
		}
	}
}
